package com.zero.manager_following.controller;

import cn.hutool.core.io.FileUtil;
import com.zero.manager_following.common.Result;
import com.zero.manager_following.interceptor.AuthAccess;
import jakarta.servlet.ServletOutputStream;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;

/**
 * 功能：文件上传下载功能
 * 作者：zero
 * 日期：2024/9/16 13:45
 */
@RestController
@RequestMapping("/file")
public class FileController {
    //文件存储的目录
    public final String ROOTPATH = System.getProperty("user.dir") + File.separator + "files";
    @Value("${ip:localhost}")
    String ip;
    @Value("${server.port}")
    String port;

//    @AuthAccess
    @PostMapping("/upload")
    public Result upload(MultipartFile file) {
        //文件名+文件类型
        String oFileName = file.getOriginalFilename();
        String main = FileUtil.mainName(oFileName);
        String ext = FileUtil.extName(oFileName);
        File saveFile;
        try {
            saveFile = new File(ROOTPATH + File.separator + main + "." + ext);
            //上传路径不存在时
            if (!FileUtil.exist(ROOTPATH)) {
                FileUtil.mkdir(ROOTPATH);
            }
            //当文件重复存在时
            if (FileUtil.exist(saveFile)) {
                //重命名文件
                saveFile = new File(ROOTPATH + "\\" +
                        main + System.currentTimeMillis() + "." + ext);
            }
            file.transferTo(saveFile);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        //返回文件下载链接
        String url = "http://" + ip + ":" + port + "/file/download/" + saveFile.getName();
        return Result.success(url);
    }


    @AuthAccess
    @GetMapping("/download/{url}")
    public void download(@PathVariable String url, HttpServletResponse response) {
        //根据url下载文件
        File file = new File(ROOTPATH + "\\" + url);
        if (FileUtil.exist(file)) {
            try (ServletOutputStream outputStream = response.getOutputStream()){
                outputStream.write(FileUtil.readBytes(file));
                outputStream.flush();
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }
    }

}
